#!/bin/bash

# 招聘系统部署脚本
# 使用方法: ./deploy.sh [环境] [版本]
# 例如: ./deploy.sh prod v1.0.0

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印彩色日志
log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

warn() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
}

# 检查参数
if [ $# -lt 1 ]; then
    error "使用方法: $0 <environment> [version]"
    error "环境选项: dev, test, prod"
    exit 1
fi

ENVIRONMENT=$1
VERSION=${2:-latest}
PROJECT_NAME="employment-system"
DOCKER_IMAGE="your-registry/${PROJECT_NAME}"

# 验证环境参数
case $ENVIRONMENT in
    dev|test|prod)
        log "部署环境: $ENVIRONMENT"
        ;;
    *)
        error "无效的环境: $ENVIRONMENT"
        error "支持的环境: dev, test, prod"
        exit 1
        ;;
esac

# 设置环境变量
case $ENVIRONMENT in
    dev)
        COMPOSE_FILE="docker-compose.dev.yml"
        ENV_FILE=".env.dev"
        ;;
    test)
        COMPOSE_FILE="docker-compose.test.yml"
        ENV_FILE=".env.test"
        ;;
    prod)
        COMPOSE_FILE="docker-compose.yml"
        ENV_FILE=".env.prod"
        ;;
esac

log "开始部署招聘系统..."
log "环境: $ENVIRONMENT"
log "版本: $VERSION"
log "Docker镜像: $DOCKER_IMAGE:$VERSION"

# 检查必要文件
if [ ! -f "$COMPOSE_FILE" ]; then
    error "Docker Compose文件不存在: $COMPOSE_FILE"
    exit 1
fi

if [ ! -f "config/env/$ENV_FILE" ]; then
    error "环境配置文件不存在: config/env/$ENV_FILE"
    exit 1
fi

# 复制环境配置文件
log "复制环境配置文件..."
cp "config/env/$ENV_FILE" .env

# 创建必要的目录
log "创建必要的目录..."
mkdir -p logs uploads data/mysql data/redis

# 设置权限
chmod 755 logs uploads
chmod 777 data/mysql data/redis

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    error "Docker未运行，请启动Docker服务"
    exit 1
fi

# 检查docker-compose是否安装
if ! command -v docker-compose &> /dev/null; then
    error "docker-compose未安装"
    exit 1
fi

# 拉取最新镜像
log "拉取Docker镜像..."
docker-compose -f $COMPOSE_FILE pull

# 停止旧容器
log "停止旧容器..."
docker-compose -f $COMPOSE_FILE down

# 清理旧镜像（可选）
if [ "$ENVIRONMENT" = "prod" ]; then
    log "清理未使用的Docker镜像..."
    docker image prune -f
fi

# 启动服务
log "启动服务..."
docker-compose -f $COMPOSE_FILE up -d

# 等待服务启动
log "等待服务启动..."
sleep 30

# 健康检查
log "进行健康检查..."
HEALTH_CHECK_URL="http://localhost:8080/api/health"
MAX_RETRIES=30
RETRY_COUNT=0

while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if curl -f -s $HEALTH_CHECK_URL > /dev/null; then
        log "健康检查通过！"
        break
    else
        warn "健康检查失败，重试中... ($((RETRY_COUNT + 1))/$MAX_RETRIES)"
        sleep 10
        RETRY_COUNT=$((RETRY_COUNT + 1))
    fi
done

if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
    error "健康检查失败，服务可能未正常启动"
    docker-compose -f $COMPOSE_FILE logs --tail=50
    exit 1
fi

# 显示服务状态
log "服务状态:"
docker-compose -f $COMPOSE_FILE ps

# 显示日志
log "最近的日志:"
docker-compose -f $COMPOSE_FILE logs --tail=20

# 部署完成
log "部署完成！"
log "访问地址:"
case $ENVIRONMENT in
    dev)
        log "  - 前端: http://localhost"
        log "  - 管理后台: http://localhost/admin"
        log "  - API文档: http://localhost:8080/swagger-ui.html"
        ;;
    test)
        log "  - 前端: http://test.your-domain.com"
        log "  - 管理后台: http://test.your-domain.com/admin"
        ;;
    prod)
        log "  - 前端: https://your-domain.com"
        log "  - 管理后台: https://your-domain.com/admin"
        ;;
esac

log "部署脚本执行完毕！"